<template>
  <div class="contentLibrary">
    <basic-container>
      <avue-crud :option="option"
                 :table-loading="loading"
                 :data="data"
                 :page.sync="page"
                 :permission="permissionList"
                 :before-open="beforeOpen"
                 v-model="form"
                 ref="crud"
                 @row-update="rowUpdate"
                 @row-save="rowSave"
                 @row-del="rowDel"
                 @search-change="searchChange"
                 @search-reset="searchReset"
                 @selection-change="selectionChange"
                 @current-change="currentChange"
                 @size-change="sizeChange"
                 @refresh-change="refreshChange"
                 @on-load="onLoad">
        <template slot="menuLeft">
          <el-button type="success" size="small" plain v-if="permissionList" icon="el-icon-upload2" @click="handleImport">导 入</el-button>
          <el-button type="warning" size="small" plain v-if="permissionList" icon="el-icon-download" @click="handleExport">导 出</el-button>
          <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.contentlibrary_delete" @click="handleDelete">删 除</el-button>
        </template>
        <template slot="jcztForm">
          <div>
            <avue-radio v-model="jczt" :dic="dic"></avue-radio>
          </div>
        </template>
      </avue-crud>
      <el-dialog title="数据导入"
                 append-to-body
                 :visible.sync="excelBox"
                 width="555px">
        <avue-form :option="excelOption" v-model="excelForm" :show-file-list="false" :upload-after="uploadAfter">
          <template slot="excelTemplate">
            <el-button type="primary" @click="handleTemplate">
              点击下载<i class="el-icon-download el-icon--right"></i>
            </el-button>
          </template>
        </avue-form>
      </el-dialog>
    </basic-container>
  </div>
</template>

<script>
  import {getList, getDetail, add, update, remove} from "@/api/xjgl/contentlibrary";
  import {mapGetters} from "vuex";
  import {getToken} from "@/util/auth";

  export default {
    data() {
      return {
        jczt:0,
        dic:[{
          label:'正常',
          value:0
        },{
          label:'异常',
          value:1
        }],
        excelBox: false,
        excelForm: {},
        excelOption: {
          submitBtn: false,
          emptyBtn: false,
          column: [{
            label: '表格导入',
            prop: 'excelFile',
            type: 'upload',
            drag: true,
            loadText: '表格导入中，请稍等',
            showFileList: false,
            span: 24,
            propsHttp: {
              fileName: 'file',
              res: 'data'
            },
            tip: '请上传 .xls,.xlsx 标准格式文件',
            action: "/api/patroContentLibrary/contentlibrary/import-contentLibrary",
            headers: {}
          },
            {
              label: '模板下载',
              prop: 'excelTemplate',
              formslot: true,
              span: 24,
            }
          ]
        },
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "巡检表类型",
              prop: "xjblx",
              width:120,
              search: true,
              align: "center",
              type:"select",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=patrol_content_library_xjblx",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dataType:"number",
              rules: [{
                required: true,
                message: "请输入巡检表类型",
                trigger: "blur"
              }]
            },
            {
              label: "巡检级别",
              prop: "xjjb",
              width:80,
              search: true,
              align: "center",
              type:"select",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=patrol_content_library_xjjb",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dataType:"number",
              rules: [{
                required: true,
                message: "请输入巡检级别",
                trigger: "blur"
              }]
            },
            {
              label: "巡检区域",
              prop: "xjqy",
              width:120,
              align: "center",
              rules: [{
                required: true,
                message: "请输入巡检区域",
                trigger: "blur"
              }]
            },
            {
              label: "巡检项目",
              prop: "xjxm",
              align: "center",
              width:"600px",
              type: "textarea",
              maxlength:500,
              span: 24,
              minRows: 6,
              rules: [{
                required: true,
                message: "请输入巡检项目",
                trigger: "blur"
              }]
            },
            {
              label: "检查状态",
              prop: "jczt",
              width:80,
              align: "center",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=patrol_content_library_jczt",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dataType:"number",
              formslot: true,
            },
            {
              label: "企业id",
              prop: "bladeDeptId",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "租户id",
              prop: "tenantId",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "创建人",
              prop: "createUser",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "创建部门",
              prop: "createDept",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "创建时间",
              prop: "createTime",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.contentlibrary_add, false),
          viewBtn: this.vaildData(this.permission.contentlibrary_view, false),
          delBtn: this.vaildData(this.permission.contentlibrary_delete, false),
          editBtn: this.vaildData(this.permission.contentlibrary_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      // 弹出导入框
      handleImport() {
        this.excelBox = true;
      },

      // 导入前判断
      beforeUpload(file, done, loading) {
        this.isFailed = false;
        var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
        const extension = testmsg === 'xls'
        const extension2 = testmsg === 'xlsx'
        if(!extension && !extension2) {
          this.$message.warning('请上传 .xls,.xlsx 标准格式文件!');
          loading()
        } else {
          done()
        }
      },

      // 导入失败后
      uploadError(error, column) {
        console.log(error,column);
        this.isFailed = true;
      },

      // 导入成功后
      uploadAfter(res, done, loading, column) {
        window.console.log(column);
        this.excelBox = false;
        this.refreshChange();
        done();
      },

      // 取消
      cancle() {
        this.page.currentPage = 1;
        this.onLoad(this.page);
      },
      handleTemplate() {
        window.open(`/api/patroContentLibrary/contentlibrary/export-template?${this.website.tokenHeader}=${getToken()}`);
      },
      handleExport() {
        this.$confirm("是否导出巡检内容表库信息?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          window.open(`/api/patroContentLibrary/contentlibrary/export-contentLibrary?${this.website.tokenHeader}=${getToken()}`);
        });
      },

      rowSave(row, done, loading) {
        row.jczt=this.jczt
        console.log(row)
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        row.jczt=this.jczt

        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
            this.jczt=this.form.jczt
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style lang="scss" scpoed>
  .contentLibrary {
    .avue-crud {
      .avue-crud__search {
        .avue-form__row:nth-child(1) {
          .el-form-item__label {
            text-align: unset;
            width: 90px !important;
          }

          .el-form-item__content {
            margin-left: 90px !important;
          }
        }
      }
    }

    .enclosure_div {
      a {
        font-size: 12px;
        color: #409eff;

        i {
          margin-right: 5px;
        }
      }
    }
  }
</style>
